package com.thenmoret.admin.controller;

import java.io.File;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.thenmoret.pojo.Article;
import com.thenmoret.pojo.PageBean;
import com.thenmoret.service.ArticleService;
import com.thenmoret.util.UUIDutil;
import com.thenmoret.util.uploadUtil;

/**
 * 后台文章管理控制层
 * @author ChenHao.Ye
 *
 * 时间:2016年6月16日下午4:05:01
 */
@RequestMapping("/admin/article")
@Controller
public class ArticleAdminController {

	@Autowired
	private ArticleService articleService;
	
	@RequestMapping(value="/update",method = RequestMethod.POST)
	public String update(Article article,HttpServletRequest request,@RequestParam("articlefile") MultipartFile file) throws Exception
	{
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();
		//原文件
		File newfile = new File(path,fileName);
		file.transferTo(newfile);
		fileName = UUIDutil.getUUID(fileName);
		//新文件
		File targetFile = new File(path,fileName);
		
		FileUtils.copyFile(newfile, targetFile);
		String newFileName = fileName.substring(0, fileName.lastIndexOf("."));
		uploadUtil.upload(newFileName, path+"/"+fileName);
		//<img src="http://7xvmfe.com1.z0.glb.clouddn.com/FmWJrqyxWinvXzx9UFtwsU3BUpLK"/>
		article.setArticleImg("<img src=\'"+"http://7xvmfe.com1.z0.glb.clouddn.com/"+newFileName+"\'>");
		if(!targetFile.exists())
		{
			targetFile.mkdirs();
		}
		articleService.updateArticle(article);
		return "/admin/ArticleManager";
	}
	
	
	/**
	 * 文章的添加或修改
	 * 主要是要传入的article实体有没有id的存在
	 * @param article
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/save",method = RequestMethod.POST)
	public String save(Article article,@RequestParam("articlefile") MultipartFile file,HttpServletRequest request) throws Exception
	{
		if(article.getArticleId() == null)
		{
			String path = request.getSession().getServletContext().getRealPath("upload");
			String fileName = file.getOriginalFilename();
			//原文件
			File newfile = new File(path,fileName);
			file.transferTo(newfile);
			fileName = UUIDutil.getUUID(fileName);
			//新文件
			File targetFile = new File(path,fileName);
			
			FileUtils.copyFile(newfile, targetFile);
			String newFileName = fileName.substring(0, fileName.lastIndexOf("."));
			uploadUtil.upload(newFileName, path+"/"+fileName);
			//<img src="http://7xvmfe.com1.z0.glb.clouddn.com/FmWJrqyxWinvXzx9UFtwsU3BUpLK"/>
			article.setArticleImg("<img src=\'"+"http://7xvmfe.com1.z0.glb.clouddn.com/"+newFileName+"\'>");
			if(!targetFile.exists())
			{
				targetFile.mkdirs();
			}
			articleService.addArticle(article);
			
			return "/admin/ArticleManager";
		}
		return null;
	}
	@RequestMapping(value="/list",method = RequestMethod.POST)
	public String list(@RequestParam(value="page",required = false) String page,
			@RequestParam(value="rows",required = false) String rows,HttpServletResponse response) throws Exception
	{
		response.setCharacterEncoding("UTF-8");
		PageBean<Article> pageBean = new PageBean();
		//传入的当前页的判断
		if(page == null || page.trim().length() == 0)
		{
			page = "1";
		}
		pageBean.setCurrPage(Integer.parseInt(page));//封装当前页
		
		//总的记录数
		Integer allRecord = articleService.findArticleList().size();
		pageBean.setAllPage(allRecord);
		
		Integer allPage = null;
		pageBean.setPageSize(Integer.parseInt(rows));
		if(pageBean.getAllPage() % pageBean.getPageSize() == 0)
		{
			allPage = pageBean.getAllPage() / pageBean.getPageSize();
		}
		else
		{
			allPage = pageBean.getAllPage() / pageBean.getPageSize()+1;
		}
		
		pageBean.setAllPageSize(allPage);
		
		Integer start = (pageBean.getCurrPage()-1) * pageBean.getPageSize();
		Integer end = pageBean.getCurrPage() * pageBean.getPageSize();
		
		List<Article> list = articleService.findByPage(start, end);
		
		pageBean.setList(list);
		Map<String,Object> map = new LinkedHashMap<>();
		/**
		 * 由于前台是easyui  他的分页会自动解析json数据  
		 * 分为total 和rows   
		 * total是整个记录
		 * rows是返回的数据源  他会和返回的json进行比对 把对应的字段输入进去
		 */
		map.put("total", pageBean.getAllPage());
		map.put("rows", pageBean.getList());
		String jsonString = JSON.toJSONString(map,true);
//		jsonString = jsonString.substring(1, jsonString.length()-1);
		PrintWriter pw = response.getWriter();
		pw.write(jsonString);
		pw.flush();
		pw.close();
		
		return null;
	}
	
	@RequestMapping(value="/delete",method=RequestMethod.GET)
	public String delete(@RequestParam("articleId") Integer id)
	{
		articleService.deleteArticle(id);
		return "/admin/ArticleManager";
	}
	
	
	
	
	
	
	
	

}
